import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:HaiPower/LocaleProvider.dart';
import 'package:HaiPower/widget_ui/home_ui.dart';
import 'package:provider/provider.dart';

import 'l10n/app_localizations.dart';
import 'listview/ListViewDemo.dart';
import 'login.dart';
import 'widget_ui/basic_demo.dart';
import 'widget_ui/bottomNavigation_bar_nv.dart';
import 'widget_ui/layout_demo.dart';
import 'widget_ui/view_demo.dart';

void main() => runApp(
  ChangeNotifierProvider(create: (_) => LocaleProvider(), child: const MyApp()),
);

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext? context) {
    return super.createHttpClient(context)
      ..badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    HttpOverrides.global = MyHttpOverrides();
    //语言监听
    final localeProvider = Provider.of<LocaleProvider>(context);
    return MaterialApp(
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        AppLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', 'US'), // English
        const Locale('zh', 'CN'), // Chinese
      ],
      locale: localeProvider.locale ?? WidgetsBinding.instance.window.locale,
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: Login(),
      theme: ThemeData(
        primarySwatch: Colors.yellow,
        appBarTheme: AppBarTheme(centerTitle: true), //标题居中显示
      ),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _currentIndex = 0;

  final List<Widget> _pages = [HomeUI(), ListViewDemo(), ViewDemo(), BasicDemo()];

  void _onIndexChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(index: _currentIndex, children: _pages),
      bottomNavigationBar: BottomNavigationBarNv(
        onIndexChanged: _onIndexChanged, // 监听索引变化
      ),
    );
  }
}
